import config from './config.js'
const app = getApp()
const network = {}
const method = ['get','post', 'delete', 'put','head']
for(let item of method){
  network[item] = ({ url, data, dataType = 'json', contentType = (item === 'post') ? 'application/json' :'application/x-www-form-urlencoded' }) => {//x-www-form-urlencoded
    if(contentType === ''){
      contentType = 'application/json'
    }
    console.log("请求Url")
    console.log(url)
    console.log("请求信息")
    console.log(data)
    console.log("请求地址")
    console.log(config.domain + config.path + url)
    let header={
      "content-type": contentType
    }
    
    if (wx.getStorageSync('token')!= null){
      header={
        "content-type": contentType,
        "Authorization": "Bearer" + " " + wx.getStorageSync('token')
      }
    }
    console.log(wx.getStorageSync('token'))
    console.log('gooooo88888888')
    console.log(header)
    return new Promise((resolve, reject)=>{
        wx.request({
          url: url.startsWith('http') ? url : config.domain + config.path + url,
          data,
          dataType,
          header: header,
          method: item.toUpperCase(),
          success: ({ data, header, statusCode, errMsg})=>{
            
            if(statusCode === 500){
              wx.showToast({title: '服务器忙，代码：' + statusCode, icon: 'none'})
              reject(data)
              wx.hideLoading()
              console.log("goodfail1");
            }
            else{
              resolve(data)
              // console.log("good")
              // console.log(data)
              // console.log("goodfail2");
              
            }
          },
          fail: (res) =>{
            reject(res)
            wx.hideLoading()
            console.log("goodfail");
            console.log(res);
          }
        })
      }
    )
  }
}

export default network